package view;

import model.OnScreen;
import model.location.Area;
import model.snippet.Snippet;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
//import android.util.Log;

public class SnippetView
{
//	private static final String TAG = SnippetView.class.getSimpleName();
	
	private float ratio = 1f;
	private Area _area;
	private float x,y,width,height = 0;
	private boolean _status = false;
	
	private boolean _inArea = true;
	private Path _path = new Path();
	private Paint _paint = new Paint();
	
	public SnippetView(Snippet _snippet)
	{
		setSnippetData(_snippet);
		
		_paint.setStyle(Paint.Style.FILL);
	}
	
	/**
	 * Save the information from the incoming snippet.
	 * @param snippet The snippet to draw.
	 */
	private void setSnippetData(Snippet snippet)
	{
		ratio = OnScreen.getInstance().getLeftTorightCodeScale();
		_area = snippet.getScreenArea();
		x = _area.getCoordinate().getX();
		y = _area.getCoordinate().getY();
		width = _area.getDimension().getWidth();
		height =_area.getDimension().getHeight();
		_status = snippet.isStatusOkay();
	}
	
	/**
	 * Checks to see if the snippet should still be drawn.
	 */
	public boolean isInArea()
	{
		return _inArea;
	}
	
	/**
	 * Delete the view of a snippet.
	 * @param snippet The snippet to delete.
	 */
	private void deleteView(Snippet snippet) 
	{
		snippet.deleteObservers();
		_inArea = false;
	}
	
	/**
	 * Handles the received update from the snippet.
	 */
	public void update(Snippet snippet)
	{
		if(snippet.isInArea())
		{
			_inArea = true;			
			setSnippetData(snippet);
		}
		else
		{
			deleteView(snippet);
		}
	}
	
	/**
	 * calculate the height-values needed to draw the path
	 */
	private float[] calculatePathPoints()
	{
		float[] yPoints;
		double margin;
		
		if(ratio >= 1.0f)
		{
			margin = ((height * ratio) - height) / 2;
			yPoints = new float[] {  y,
									y + (float) margin,
									y + height - (float) margin,
									y + height,
									y };
		}
		else
		{
			margin = ((height * (1/ratio)) - height) / 2;
			yPoints = new float[] { y + (float) margin,
									y,
									y + height,
									y + height - (float) margin,
									y + (float) margin };
		}
		
		return yPoints;		
	}
	
	/**
	 * Creates a path representing the snippet screen Area.
	 */
	public Path getDrawableSnippetPath()
	{
		float[] yPoints = calculatePathPoints();
	
		_path.reset();
		
		_path.moveTo(x, yPoints[0]);
		_path.lineTo(x + width, yPoints[1]);
		_path.lineTo(x + width, yPoints[2]);
		_path.lineTo(x, yPoints[3]);
		_path.lineTo(x, yPoints[4]);
		
		return _path;
	}
	
	/**
	 * Sets the color of a snippet by their status value.
	 * @return The paint object used for drawing the snippet.
	 */
	public Paint getSnippetPaint()
	{
		int color = _status ? Color.GREEN : Color.RED;
		_paint.setColor(color);
		
		return _paint;
	}
	
}